package com.wpg.demo.spring.xml.validation;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

/**
 * @author ChangWei Li
 * @version 2017-02-22 13:39
 */
public class PersonValidator implements Validator {


    @Override
    public boolean supports(Class<?> clazz) {
        return Person.class.isAssignableFrom(clazz);
    }

    @Override
    public void validate(Object target, Errors errors) {
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "name.empty");
        Person person = (Person) target;

        if (person.getAge() < 0) {
            errors.rejectValue("age", "age.toosmall");
        } else if (person.getAge() > 110) {
            errors.rejectValue("age", "age.toobig");
        }
    }
}
